#include "mainwindow.h"
#include "qevent.h"
#include "ui_mainwindow.h"
#include <QThread>
#include <QPoint>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // progressDialog = new QDialog(this);
    // uploadBar = new QProgressBar(progressDialog);
    // processBar = new QProgressBar(progressDialog);












    this->setWindowTitle("工时测量系统");
    ui->label_10->setFixedSize(40, 40);
    QString styleSheet = QString("background-color: #b30628; border-radius: %1px;").arg(ui->label_10->width() / 2);
    ui->label_10->setStyleSheet(styleSheet);
    m_timer_run = new QTimer;


    player = new QMediaPlayer;

    manager = new QNetworkAccessManager;

    manager_2 = new QNetworkAccessManager;

    player->setVideoOutput(ui->videoWidget);
    QTimer::singleShot(3000,[this]()
    {
        QNetworkRequest request(QUrl("http://localhost:12345/process_videos"));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        QJsonObject jsonRoot;
        jsonRoot["fileSize"] = 0;
        QJsonArray jsonFileList;
        QJsonObject jsonFile;
        jsonFile["filePath"] = "";
        jsonRoot["fileList"] = jsonFileList;
        QByteArray sendDataglobalConfig = QJsonDocument(jsonRoot).toJson();

        QNetworkReply *reply = manager->post(request, sendDataglobalConfig);
        QObject::connect(reply, &QNetworkReply::finished, [reply,this]() {
            if (reply->error() == QNetworkReply::NoError) {
                algorithm++;
                if(algorithm==2)
                {
                    QString styleSheet = QString("background-color: green; border-radius: %1px;").arg(ui->label_10->width() / 2);
                    ui->label_10->setStyleSheet(styleSheet);
                }
            }
            reply->deleteLater();
        });
    });
    QTimer::singleShot(3000,[this]()
    {
        QNetworkRequest request_2(QUrl("http://localhost:54321/process_pose_videos"));
        request_2.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        QJsonObject jsonData;
        QJsonArray fileList_2;
        jsonData["fileList"] = fileList_2;
        QJsonDocument doc(jsonData);
        QByteArray replydata = doc.toJson();
        QNetworkReply *reply = manager_2->post(request_2, replydata);
        QObject::connect(reply, &QNetworkReply::finished, [reply,this]() {
            if (reply->error() == QNetworkReply::NoError) {
                algorithm++;
                if(algorithm==2)
                {
                    QString styleSheet = QString("background-color: green; border-radius: %1px;").arg(ui->label_10->width() / 2);
                    ui->label_10->setStyleSheet(styleSheet);
                }
            }
            reply->deleteLater();

        });
    });




    //启动所有线程
    startThread();

    initInterface();

}

MainWindow::~MainWindow()
{
    delete ui;
    delete player;
    delete manager;
    delete manager_2;

    lastthread.exit();
    lastthread.wait();
    delete m_lastvideo;

    sendthread.exit();
    sendthread.wait();
    delete m_sendvideo;

}

void MainWindow::initInterface()
{
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    //显示时间
    m_timer=new QTimer(this);
    m_timer->start(400);
    QString dateString = QDate::currentDate().toString("yyyy-MM-dd");
    QString timeString = QTime::currentTime().toString("hh:mm:ss");
    ui->label_4->setText(timeString);
    ui->label_6->setText(dateString);
    connect(m_timer,&QTimer::timeout,this,[this](){
        QString dateString = QDate::currentDate().toString("yyyy-MM-dd");
        QString timeString = QTime::currentTime().toString("hh:mm:ss");
        ui->label_4->setText(timeString);
        ui->label_6->setText(dateString);
        //所有结束复位
        if(flag_final>=2)
        {
            ui->pushButton->setEnabled(true);
            ui->pushButton_3->setEnabled(true);
            for(auto &list : temp_listfile)
            {
                for (auto& pair : listpair) {
                    for (auto& value : pair.second) {
                        if(value.first==list.first)
                        {
                            value.second=list.second;
                        }
                    }
                }
            }

            m_progress.hide();
            // QList<QPair<QString,QVector<QPair<QString,QJsonArray>>>> listpair;
            for (const auto& outerPair : listpair) {
                qDebug() << "Outer Pair First:" << outerPair.first;
                QJsonArray jsonArray;

                for (const auto& innerPair : outerPair.second) {
                    qDebug()<<innerPair.first<<innerPair.second;
                    const QJsonArray& innerArray = innerPair.second;
                    for (const auto& value : innerArray) {
                        jsonArray.append(value);
                    }
                }
                handle(outerPair.first,jsonArray);
                QListWidgetItem *item = new QListWidgetItem(outerPair.first);
                ui->listWidget_2->addItem(item);

                for (int i = 0; i < ui->listWidget->count(); ++i) {
                    QListWidgetItem* item = ui->listWidget->item(i);
                    if (item->text() == outerPair.first) {
                        delete ui->listWidget->takeItem(i);
                        --i;
                    }
                }
            }
            a1=0;
            a2=0;
            a3=0;
            flag_final=0;
            fileList.clear();
            requestQueue.clear();
            listpair.clear();
            temp_listfile.clear();
        }
    });

    //设置LOGO
    QPixmap pixmap(":/image/LOGO.png");
    ui->label_2->setPixmap(pixmap);
    ui->label_2->setScaledContents(true);

    ui->videoWidget->setStyleSheet("background-color: black;");

    // 设置样式表
    ui->label_8->setFixedSize(40, 40);
    QString styleSheet = QString("background-color: #b30628; border-radius: %1px;").arg(ui->label_8->width() / 2);
    ui->label_8->setStyleSheet(styleSheet);


    appDirPath = QCoreApplication::applicationDirPath();


    connect(&m_filename,&filename::fileName,this,[this](QString filename1,QString filename2){
        // 检查新文件名是否已存在（可选，但推荐）
        if (QFile::exists(filename2)) {
            fileList.append(filename2);
            QListWidgetItem *item = new QListWidgetItem(filename2);
            ui->listWidget->addItem(item);
        } else {
            // 重命名文件
            if (QFile::rename(filename1, filename2)) {
                // QMessageBox::information(&mainWindow, tr("Success"), tr("File renamed successfully to %1").arg(newFileName));
                fileList.append(filename2);
                QListWidgetItem *item = new QListWidgetItem(filename2);
                ui->listWidget->addItem(item);
            } else {
            }
        }

    });


}


//添加文件
void MainWindow::on_pushButton_clicked()
{
    //获取视频文件
    QString fileName = QFileDialog::getOpenFileName(this,tr("Open File"), "", tr("Files (*.mp4)"));
    if(!fileName.isEmpty())
    {
        if(ui->listWidget->count()>=10)
        {
            QMessageBox::information(this, "提示", "文件超出");
            return ;
        }
        for (int i = 0; i < ui->listWidget->count(); ++i) {
            QListWidgetItem* item = ui->listWidget->item(i);
            if (item->text() == fileName) {
                QMessageBox::information(this, "提示", "文件重复");
                return ;
            }
        }
        QRect screenGeometry = this->childrenRect();
        int screenWidth = screenGeometry.width();
        int screenHeight = screenGeometry.height();
        int centerX = screenWidth / 2 - m_filename.width() / 2;
        int centerY = screenHeight / 2 - m_filename.height() / 2;
        m_filename.move(centerX, centerY);
        m_filename.setf(fileName);
        m_filename.exec();

    }
}

//切割选择视频，发送
void MainWindow::videoProcessing()
{
    //获取所有片段
    for (const QString &i : fileList) {
        int getTotalFrame = getTotalFrames(i.toStdString());
        if(getTotalFrame>2000)
        {
            for(int i=getTotalFrame;i>0;i-=2000)
                a1++;
        }
        else
        {
            a1++;
        }
    }

    //开始进度
    m_progress.setprogress(a2*100.0/a1,a3*100.0/a1);

    m_sendvideo->_start();

    m_timer_run->start(1000);
    connect(m_timer_run,&QTimer::timeout,this,[this]()
    {
        if(sendFlag && !requestQueue.isEmpty())
        {
            sendFlag = false;
            sendNextRequest(requestQueue.at(0));
            requestQueue.removeFirst();
        }
        if(a3 == a1)
        {
            m_timer_run->stop();
            flag_final++;
            qDebug()<<"flag_final数据"<<flag_final<<"a1"<<a1<<"a2"<<a2;

            // emit success();
        }
    });
    QRect screenGeometry = this->childrenRect();
    int screenWidth = screenGeometry.width();
    int screenHeight = screenGeometry.height();
    int centerX = screenWidth / 2 - m_progress.width() / 2;
    int centerY = screenHeight / 2 - m_progress.height() / 2;
    m_progress.move(centerX, centerY);
    m_progress.exec();
}

//视频帧率
double MainWindow::getVideoFPS(const std::string &videoPath)
{
    cv::VideoCapture cap(videoPath);
    if (!cap.isOpened()) {
        qDebug() << "无法打开视频文件: " << QString::fromStdString(videoPath);
        return -1;
    }
    double fps = cap.get(cv::CAP_PROP_FPS);
    cap.release();
    return fps;
}
//视频总帧率
int MainWindow::getTotalFrames(const std::string &videoPath)
{
    cv::VideoCapture cap(videoPath);
    if (!cap.isOpened()) {
        qDebug() << "无法打开视频文件: " << QString::fromStdString(videoPath);
        return -1;
    }
    int totalFrames = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_COUNT));
    cap.release();
    return totalFrames;
}

//骨骼视频获取
void MainWindow::bonesVideo()
{
    QNetworkRequest request_2(QUrl("http://localhost:54321/process_pose_videos"));
    request_2.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject jsonData;
    QJsonArray fileList_2;
    for(QString &filename : fileList)
    {
        QJsonObject file;
        file["filePath"] =filename;
        fileList_2.append(file);
    }
    jsonData["fileList"] = fileList_2;

    QJsonDocument doc(jsonData);
    QByteArray replydata = doc.toJson();
    QNetworkReply *reply = manager_2->post(request_2, replydata);
    QObject::connect(reply, &QNetworkReply::finished, [reply,this]() {
        //骨骼结束
        bonesFlag = true;
        QString styleSheet = QString("background-color: green; border-radius: %1px;").arg(ui->label_8->width() / 2);
        ui->label_8->setStyleSheet(styleSheet);
        reply->deleteLater();
    });
}
//发送
void MainWindow::sendNextRequest(QByteArray sendData)
{
    QNetworkRequest request(QUrl("http://localhost:12345/process_videos"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QNetworkReply *reply = manager->post(request, sendData);
    QObject::connect(reply, &QNetworkReply::finished, [reply,this]() {
        //工艺算法进度
        a3++;
        m_progress.setprogress(a2*100.0/a1,a3*100.0/a1);

        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
            if (!jsonDoc.isNull() && jsonDoc.isObject()) {
                QJsonObject jsonObj = jsonDoc.object();
                analysis(jsonObj);
            } else {
                qDebug() << "Failed to parse JSON response:" << responseData;
            }
            qDebug() << "Server response:" << responseData;
        } else {
            qDebug() << "Request error:" << reply->errorString();
        }
        reply->deleteLater();
        sendFlag = true;
    });
}
//创建文件夹
void MainWindow::mkdir(const QString &path)
{


    QDir dir;
    if (!dir.exists(path)) {
        if (dir.mkpath(path)) {
            qDebug() << "文件夹 " << path << " 创建成功";
        } else {
            qDebug() << "文件夹 " << path << " 创建失败";
        }
    } else {
        qDebug() << "文件夹 " << path << " 已经存在";
        clearFolder(path);
        if (dir.mkpath(path)) {
            qDebug() << "文件夹 " << path << " 创建成功";
        } else {
            qDebug() << "文件夹 " << path << " 创建失败";
        }
    }
}

bool MainWindow::clearFolder(const QString &folderPath)
{
    QDir dir(folderPath);
    if (!dir.exists()) {
        qDebug() << "指定的文件夹不存在: " << folderPath;
        return false;
    }

    // 遍历文件夹中的所有条目
    QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
    for (const QFileInfo& entry : entries) {
        if (entry.isFile()) {
            // 如果是文件，直接删除
            if (!QFile::remove(entry.absoluteFilePath())) {
                qDebug() << "无法删除文件: " << entry.absoluteFilePath();
                return false;
            }
        } else if (entry.isDir()) {
            // 如果是文件夹，递归调用 clearFolder 函数进行清除
            if (!clearFolder(entry.absoluteFilePath())) {
                return false;
            }
            // 删除空文件夹
            if (!dir.rmdir(entry.absoluteFilePath())) {
                qDebug() << "无法删除文件夹: " << entry.absoluteFilePath();
                return false;
            }
        }
    }
    return true;
}


//上传发送
void MainWindow::on_pushButton_3_clicked()
{
    if(fileList.isEmpty())
        return;
    if(!bonesFlag)
    {
        QMessageBox::information(this, "提示", "请等待骨骼视频获取结束");
        return;
    }
    ui->pushButton->setEnabled(false);
    ui->pushButton_3->setEnabled(false);
    bonesFlag = false;
    QString styleSheet = QString("background-color: #b30628; border-radius: %1px;").arg(ui->label_8->width() / 2);
    ui->label_8->setStyleSheet(styleSheet);
    clearFolder(appDirPath+"/temp/");
    videoProcessing();

}
//双击显示表单
void MainWindow::on_listWidget_2_itemDoubleClicked(QListWidgetItem *item)
{
    QFileInfo fileInfo(item->text());
    QString fileName = fileInfo.fileName();
    QString savepath=appDirPath+"/data/"+fileName+"/"+fileName+".csv";
    Form *form=new Form(savepath);
    form->showMaximized();
}
//右击删除
void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    QPoint globalPos = ui->listWidget->mapToGlobal(pos);
    QMenu contextMenu(this);
    QAction action("删除", this);
    connect(&action, &QAction::triggered, this, [&](){
        QListWidgetItem* currentItem = ui->listWidget->currentItem();
        if (currentItem) {
            QString str = currentItem->text();
            // fileList.removeAll(str);
            delete ui->listWidget->takeItem(ui->listWidget->row(currentItem));
        }
    });
    contextMenu.addAction(&action);
    contextMenu.exec(globalPos);
}

//数据解析
void MainWindow::analysis(QJsonObject obj)
{
    int fileSize = obj["fileSize"].toInt();
    qDebug() << "fileSize:" << fileSize;
    QJsonArray fileListArray = obj["fileList"].toArray();
    for (const QJsonValue &fileListValue : fileListArray) {
        QJsonObject fileListItem = fileListValue.toObject();
        QString filePath = fileListItem["filePath"].toString();
        // int listSize = fileListItem["listSize"].toInt();
        QJsonArray listArray = fileListItem["list"].toArray();
        QPair<QString,QJsonArray> pair(filePath,listArray);
        temp_listfile.append(pair);

        // for (auto& pair : listpair) {
        //     for (auto& value : pair.second) {
        //         if(value.first==filePath)
        //         {
        //             value.second=listArray;
        //         }
        //     }
        // }
    }
}
//0空动作
//1拿取
//2缝纫
//数据处理
void MainWindow::handle(QString filePath, QJsonArray listArray)
{

    double fps=getVideoFPS(filePath.toStdString());
    int first=0;
    int next=0;
    for (int i = 0; i < listArray.size(); ++i) {
        if(listArray[i].toInt()!=1)
            first++;
        else
            break;
    }
    next=first;
    QVector<QPair<int, int>> vector;
    int count1 = 0, count2 = 0, count0 = 0;
    int currentValue = -1; // 用于跟踪当前正在计数的值
    for (int i = 0; i < listArray.size(); ++i) {
        int value = listArray[i].toInt();
        if (value == 1) {
            if (currentValue == 0) {
                    vector.append(QPair<int, int>(0, count0));
                    count0 = 0;
            } else if (currentValue == 2) {
                    vector.append(QPair<int, int>(2, count2));
                    count2 = 0;
            }
            currentValue = 1;
            count1++;
        } else if (value == 2 && currentValue!=-1) {
            if (currentValue == 0) {
                    vector.append(QPair<int, int>(0, count0));
                    count0 = 0;
            } else if (currentValue == 1) {
                    vector.append(QPair<int, int>(1, count1));
                    count1 = 0;
            }
            currentValue = 2;
            count2++;
        } else if (value == 0 && currentValue!=-1) {
            if (currentValue == 1) {
                    vector.append(QPair<int, int>(1, count1));
                    count1 = 0;
            } else if (currentValue == 2) {
                    vector.append(QPair<int, int>(2, count2));
                    count2 = 0;
            }
            currentValue = 0;
            count0++;
        }
    }
    // 循环结束后，添加剩余的计数
    if (currentValue == 1 && count1 != 0) {
        vector.append(QPair<int, int>(1, count1));
    } else if (currentValue == 2 && count2 != 0) {
        vector.append(QPair<int, int>(2, count2));
    } else if (currentValue == 0 && count0 != 0) {
        vector.append(QPair<int, int>(0, count0));
    }
    QVector<QVector<QPair<int, int>>> segments;
    QVector<QPair<int, int>> current_segment;
    // for (const auto& action : vector) {
    //     if (action.first == 1) {
    //         if (!current_segment.empty()) {
    //             segments.push_back(current_segment);
    //             current_segment.clear();
    //         }
    //         current_segment.push_back(action);
    //     } else {
    //         current_segment.push_back(action);
    //     }
    //     if (&action == &vector.back() && !current_segment.empty()) {
    //         segments.push_back(current_segment);
    //     }
    // }
    for (const auto& action : vector) {
        current_segment.push_back(action);
        if (action.first == 2) {
            segments.push_back(current_segment);
            current_segment.clear();
        }
    }

    // 处理最后一段如果没有以2结尾的情况
    if (!current_segment.empty()) {
        segments.push_back(current_segment);
    }

    // 打印结果
    for (const auto& subSegment : segments) {
        for (const auto& pair : subSegment) {
            std::cout << "(" << pair.first << ", " << pair.second << ") ";
        }
        std::cout << std::endl;
    }
    // 创建 QDir 对象，并尝试创建文件夹
    QFileInfo fileInfo(filePath);
    QString fileName = fileInfo.fileName();

    QStringList parts = fileName.split('_'); // 按_分割

    // 提取各时间单元（注意索引位置）
    int year = parts[0].left(4).toInt();
    int month = parts[1].toInt();
    int day = parts[2].toInt();
    int hour = parts[3].toInt();
    int minute = parts[4].toInt();
    int second = parts[5].left(2).toInt(); // 处理.mp4后缀

    QString folderPath="./data/"+fileName;
    mkdir(folderPath);
    QMap<int,int> time;
    //数据以csv保存
    File fileHandler;
    QStringList header = {"序号", "开始时间", "结束时间", "拿取时间", "缝纫时间", "其他时间","总时间","输出视频"};
    QString savepath=folderPath+"/"+fileName+".csv";
    QVector<QVector<QString>> tableData;
    QStringList data ;
    // 输出每个分段的内容
    for (int i = 0; i < segments.size(); ++i) {
        //记录大步骤
        qDebug() << "Segment" << i + 1 << ":";
        qDebug()<<segments[i];
        QVector<QString> myVector = {"0", "0", "0", "0", "0" ,"0","0",""};
        for (const auto& action : segments[i]) {
            switch (action.first) {
            case 0:
                next=next+action.second;
                qDebug() << "空动作" << QString::number(action.second / fps, 'f', 2) << "s";
                myVector[5]=QString::number(action.second / fps, 'f', 2);
                myVector[0]=QString::number(i + 1);
                break;
            case 1:
                next=next+action.second;
                qDebug() << "拿取" << QString::number(action.second / fps, 'f', 2) << "s";
                myVector[3]=QString::number(action.second / fps, 'f', 2);
                myVector[0]=QString::number(i + 1);
                break;
            case 2:
                next=next+action.second;
                qDebug() << "缝纫" << QString::number(action.second / fps, 'f', 2) << "s";
                myVector[4]=QString::number(action.second / fps, 'f', 2);
                myVector[0]=QString::number(i + 1);
                break;
            default:
                qDebug() << "未知动作";
                break;
            }   
        }
        time[next-first]=first;

        map_mp4[next-first]=i;

        qDebug()<<"wt"<<next<<first;
        //开始-结束
        myVector[1]=fpsToTimeString(first,fps,true,hour,minute,second);
        myVector[2]=fpsToTimeString(next,fps,true,hour,minute,second);
        myVector[6]=QString::number((next-first) / fps, 'f', 2);
        tableData.append(myVector);
        first=next;
    }
    //遍历写入文件

    // for (const QVector<QString> &row : tableData) {
    //     QString csvRow;
    //     for (int i = 0; i < row.size(); ++i) {
    //         csvRow.append(row[i]);
    //         if (i < row.size() - 1) {
    //             csvRow.append(","); // 在不是最后一个元素时添加逗号
    //         }
    //     }
    //     data.append(csvRow);
    // }

    //最小
    if(time.size()<=9)
    {
        mkdir(folderPath+"/MIN/");
        QMap<int, int>::iterator i;
        for (i = time.begin(); i != time.end(); ++i) {

            tableData[map_mp4[i.key()]][7]=QString::number(i.value())+"_"+QString::number(i.key()/getVideoFPS(filePath.toStdString()),'f', 2)+"s.mp4";

            // for (const QVector<QString> &row : tableData) {
            //     QString csvRow;
            //     for (int i = 0; i < row.size(); ++i) {
            //         csvRow.append(row[i]);
            //         if (i < row.size() - 1) {
            //             csvRow.append(","); // 在不是最后一个元素时添加逗号
            //         }
            //     }
            //     data.append(csvRow);
            // }


            QString savepath=folderPath+"/MIN/";
            QPair<QString, QString> pair1={filePath,savepath};
            QPair<int, int> pair2={i.value(),i.key()+i.value()};
            QPair<QPair<QString, QString>, QPair<int, int> > file={pair1,pair2};
            m_lastvideo->setfile(file);
        }
    }
    //最小和最大
    if(time.size()>9)
    {
        mkdir(folderPath+"/MIN/");
        mkdir(folderPath+"/MAX/");
        int j=0;
        QMap<int, int>::iterator i;
        for (i = time.begin(); i != time.end(); ++i) {
            if(j>=10)
                break;

            tableData[map_mp4[i.key()]][7]=QString::number(i.value())+"_"+QString::number(i.key()/getVideoFPS(filePath.toStdString()),'f', 2)+"s.mp4";
            QString savepath=folderPath+"/MIN/";
            QPair<QString, QString> pair1={filePath,savepath};
            QPair<int, int> pair2={i.value(),i.key()+i.value()};
            QPair<QPair<QString, QString>, QPair<int, int> > file={pair1,pair2};
            m_lastvideo->setfile(file);

            j++;
        }
        int j2=0;
        QMap<int, int>::iterator i2;
        for (i2 = time.begin(),i2=i2+time.size()-10; i2 != time.end() && j2 < 10; ++i2) {
            tableData[map_mp4[i.key()]][7]=QString::number(i.value())+"_"+QString::number(i.key()/getVideoFPS(filePath.toStdString()),'f', 2)+"s.mp4";

            QString savepath=folderPath+"/MAX/";
            QPair<QString, QString> pair1={filePath,savepath};
            QPair<int, int> pair2={i2.value(),i2.key()+i2.value()};
            QPair<QPair<QString, QString>, QPair<int, int> > file={pair1,pair2};
            m_lastvideo->setfile(file);
            j2++;
        }
    }

    for (const QVector<QString> &row : tableData) {
        QString csvRow;
        for (int i = 0; i < row.size(); ++i) {
            csvRow.append(row[i]);
            if (i < row.size() - 1) {
                csvRow.append(","); // 在不是最后一个元素时添加逗号
            }
        }
        data.append(csvRow);
    }
    fileHandler.write(savepath, header, data, true);

    {
        // 使用迭代器遍历 QMap
        QMap<int, int>::const_iterator it;
        for (it = time.constBegin(); it != time.constEnd(); ++it) {
            qDebug() << "Key:" << it.key() << "Value:" << it.value();
        }
    }
}
//帧率转时间

QString MainWindow::fpsToTimeString(int totalFrames, double fps, bool flag, int h, int m, int s)
{
    if(flag)
    {
        double totalSeconds = static_cast<double>(totalFrames) / fps;
        int hours = static_cast<int>(totalSeconds / 3600);
        totalSeconds -= hours * 3600;
        int minutes = static_cast<int>(totalSeconds / 60);
        int seconds = static_cast<int>(totalSeconds - minutes * 60);
        //进位
        if(s+seconds>=60)
        {
            s-=60;
            m++;
        }
        if(m+minutes>=60)
        {
            m-=60;
            h++;
        }
        if(h+hours>=24)
        {
            h-=24;
        }


        // 构建并返回格式化的时间字符串
        QString timeString = QString("%1:%2:%3")
                                 .arg(hours+h, 2, 10, QChar('0'))
                                 .arg(minutes+m, 2, 10, QChar('0'))
                                 .arg(seconds+s, 2, 10, QChar('0'));
        return timeString;
    }

    double totalSeconds = static_cast<double>(totalFrames) / fps;
    int hours = static_cast<int>(totalSeconds / 3600);
    totalSeconds -= hours * 3600;
    int minutes = static_cast<int>(totalSeconds / 60);
    int seconds = static_cast<int>(totalSeconds - minutes * 60);
    // 构建并返回格式化的时间字符串
    QString timeString = QString("%1:%2:%3")
                             .arg(hours, 2, 10, QChar('0'))
                             .arg(minutes, 2, 10, QChar('0'))
                             .arg(seconds, 2, 10, QChar('0'));
    return timeString;

}

//启动所有线程
void MainWindow::startThread()
{
    m_server_1 = new server(1);
    m_server_2 = new server(2);
    QThreadPool::globalInstance()->start(m_server_1);
    QThreadPool::globalInstance()->start(m_server_2);

    m_lastvideo = new lastVideo();
    m_lastvideo->moveToThread(&lastthread);
    connect(&lastthread,&QThread::started,m_lastvideo,&lastVideo::startRun);
    lastthread.start();

    m_sendvideo = new sendVideo(fileList,appDirPath,listpair);
    m_sendvideo->moveToThread(&sendthread);
    connect(&sendthread,&QThread::started,m_sendvideo,&sendVideo::startRun);
    // 启动线程
    sendthread.start();

    connect(m_sendvideo,&sendVideo::OK,this,[this](const QString& outputVideo){
        //切割进度
        a2++;
        m_progress.setprogress(a2*100.0/a1,a3*100.0/a1);

        QJsonObject jsonRoot;
        jsonRoot["fileSize"] = 1;
        QJsonArray jsonFileList;
        QJsonObject jsonFile;
        jsonFile["filePath"] = outputVideo;
        jsonFileList.append(jsonFile);
        jsonRoot["fileList"] = jsonFileList;
        QByteArray sendDataglobalConfig = QJsonDocument(jsonRoot).toJson();
        qDebug()<<"send"<<sendDataglobalConfig;
        requestQueue.append(sendDataglobalConfig);

    });

    connect(m_sendvideo,&sendVideo::end,this,[this](){
        flag_final++;
        qDebug()<<"flag_final切割结束"<<flag_final;
        bonesVideo();
    });


}
//单击播放视频
void MainWindow::on_listWidget_2_itemClicked(QListWidgetItem *item)
{
    QUrl mediaUrl;
    if(bonesFlag)
    {
        QFileInfo fileInfo(item->text());
        QString fileName = fileInfo.path() + "/" + fileInfo.completeBaseName() + "_keypoints.mp4";
        mediaUrl = QUrl::fromLocalFile(fileName);

    }
    else
    {
        mediaUrl = QUrl::fromLocalFile(item->text());
    }
    qDebug()<<"bonesFlag"<<bonesFlag<<mediaUrl;
    player->setMedia(mediaUrl);
    player->play();
}
